<template>
  <div class="app-container">
    <div class="customContainer" v-show="tab_view==1">
      <!-- 搜索头 -->
      <el-form :inline="true" :model="formInline" class="demo-form-inline" size="small">
        <el-form-item>
          <el-date-picker style="width:240px" v-model="pickerDate" value-format="yyyy-MM-dd" type="daterange" align="right" unlink-panels range-separator="-"
                          :clearable="false" start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions"></el-date-picker>
        </el-form-item>
        <el-form-item>
          <span style="color: #888;">状态：</span>
          <el-select
              placeholder="模板状态"
              v-model="formInline.enable"
              style="width:100px"
              filterable
          >
            <el-option
                v-for="item in template_listState"
                :key="item.id"
                :label="item.name"
                :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select
              placeholder="选择模板"
              v-model="formInline.tem_type"
              style="width:150px"
              filterable
          >
            <el-option
                v-for="item in template_list"
                :key="item.id"
                :label="item.name"
                :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item >
          <el-input v-show="formInline.tem_type==0" style="width: 200px" v-model="formInline.name" placeholder="请输入模板名称" @keyup.enter.native="listArray">
          </el-input>
          <el-input v-show="formInline.tem_type==1" style="width: 200px" v-model="formInline.code" placeholder="请输入模板CODE" @keyup.enter.native="listArray">
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="listArray">搜索</el-button>
        </el-form-item>
        <el-button class="pull-right" type="primary" size="small" @click="addTypeClick()">添加模板</el-button>
      </el-form>

       <!--       表格内容-->
      <el-table highlight-current-row :data="list" border size="mini" v-loading.body="listLoading"
                :default-sort = "{prop: 'create_time', order: 'descending'}">
        <el-table-column align="center" label='序号' width="50">
          <template slot-scope="scope">{{scope.$index+1+(currentPage-1)*20}}</template>
        </el-table-column>
        <el-table-column align="center" label="模板名称" prop="name"></el-table-column>
        <el-table-column align="center" label="模板内容">
          <template slot-scope="scope">
            <div class="longlinks">{{scope.row.content}}</div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="模板类型">
          <template slot-scope="scope">
            <div>{{scope.row.type==1?'推广短信':'通知短信'}}</div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="模板CODE" prop="code"></el-table-column>
        <el-table-column align="center" label="创建时间" prop="create_time" sortable></el-table-column>
        <el-table-column align="center" label='操作' width="330">
          <template slot-scope="scope">
            <el-button  type="primary" plain size="mini" @click="goPage(scope.row)">发短信</el-button>
            <el-button  type="primary" plain size="mini" @click="addTypeClick(scope.row)">详情</el-button>
            <el-button  type="primary" plain size="mini" v-if="scope.row.is_enable==1" @click="templateEnable(scope.row,0)">停用</el-button>
            <el-button  type="primary" plain size="mini" v-if="scope.row.is_enable==0" @click="templateEnable(scope.row,1)">启用</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

      <!--     新增模板-->
    <div v-show="tab_view==2" class="customContainer">
      <el-button class="pull-left" type="primary" size="small" @click="backClick">返 回</el-button>
      <div class="tab_title">{{top_title}}</div>
      <div class="info">
        <el-form
            :model="infoForm"
            ref="infoForm"
            :rules="rules"
            :disabled="isDisabled"
            label-width="80px"
        >
          <el-form-item label="模板来源" label-width="100px">
            <el-radio v-model="infoForm.source" label="1">阿里云</el-radio>
          </el-form-item>
          <el-form-item label="模板类型" label-width="100px" prop="type">
            <template>
              <el-radio-group v-model="infoForm.type">
                <el-radio label="1">推广短信（0.055元/条）</el-radio>
                <el-radio label="2">通知短信（0.045元/条）</el-radio>
              </el-radio-group>
              <div class="colortext" v-show="infoForm.type==1">
                <p>1.向手机号码发送的包含推广信息的短信，短信内容为经过审核的模板内容，不支持通过变量替换实现个性短信定制。</p>
                <p>2.通常用于向注册用户和潜在客户发送通知和推广信息，包括促销活动通知、业务推广、新产品宣讲、会员关怀等商品与活动的推广信息，可以增加企业产品曝光率、提高产品和企业的知名度。</p>
              </div>
              <div class="colortext"  v-show="infoForm.type==2">
                <p>1.向手机号码发送的通知类短信，支持通过变量替换实现个性短信定制。</p>
                <p>2.通常用于向注册用户下发系统相关信息，包括升级或维护、服务开通、价格调整、 订单确认、物流动态、消费确认、 支付通知等普通通知短信。</p>
              </div>
            </template>
          </el-form-item>
          <el-form-item label="模板CODE" label-width="100px" prop="code">
            <el-input
                :maxlength="15"
                placeholder="模板CODE由第三方平台创建模板审核通过后获得"
                v-model="infoForm.code"
                style="width:80%"
            ></el-input>
          </el-form-item>
          <el-form-item label="模板名称" label-width="100px" prop="name">
            <el-input
                :maxlength="15"
                placeholder="请输入名称"
                v-model="infoForm.name"
                style="width:80%"
                show-word-limit
            ></el-input>
          </el-form-item>
          <el-form-item label="模板内容" label-width="100px" prop="content">
            <el-input
                type="textarea"
                :maxlength="70"
                :rows="3"
                v-model="infoForm.content"
                style="width:80%"
                :placeholder="infoForm.type==2?'变量格式：${name}; \n示例：【洞见云】尊敬的${name}，您已经${time}天没来本店了，赠送您1份福利，请打开${link}进入小程序进行查看。':'【洞见云】尊敬的用户，您已经很久没来本店了，本店最近有新活动，快来看看吧。'"
                show-word-limit
            ></el-input>
          </el-form-item>
          <el-form-item label="注意事项:" label-width="100px" label-color="red">
            <div class="colortext" v-show="infoForm.type==1">
              <p>1.推广短信支持退订（模板内容结尾会自动加上"回T退订"，占模板内容4个字数）</p>
              <p>2.推广短信不支持加变量</p>
              <p>3.推广短信建议在结尾加上空格或字符，便于区分营销内容</p>
              <p>4.不能发送贷款/借款/中奖/抽奖类信息，不支持金融理财&房产通知类短信（验证码除外）</p>
            </div>
            <div class="colortext" v-show="infoForm.type==2">
              <p>1.不能发送营销/贷款/借款/中奖/抽奖类信息，不支持金融理财&房产通知类短信（验证码除外）</p>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <div style="text-align:right;margin-bottom:20px" v-if="!isDisabled">
        <el-button
            @click="editClick()"
            type="primary"
            size="small"
        >保存</el-button>
      </div>
    </div>

    <!-- 自定义底部 -->
    <div class="bottom_box" v-show="tab_view==1">
      <el-pagination class="pull-left" background @current-change="handleCurrentChange" :current-page.sync="currentPage" :page-size="20"
                     layout="prev, pager, next, jumper" :total="totalDataNumber">
      </el-pagination>
    </div>
  </div>
</template>

<script>
import {
  createTemplate,
  getLinkInfoPage,
  getLinkInfo,
  templateEnable
} from "@/api/operation/temManagement";
import {
  pickerOptionsF,
  optionMaxTime369,
  pickerDateOneMonth
} from "@/utils";
import {
  notCharmap,
} from "@/utils/validate";
export default {
  data(){
    const vTrad = (rule, value, callback) => {
      if (!this.infoForm.type) {
        callback(new Error("请选择模板类型"));
      } else {
        callback();
      }
    };
    const vName = (rule, value, callback) => {
        if (!value) {
          callback(new Error("请输入模板名字（1-15个字符）"));
        } else {
          if (!notCharmap(value)) {
            callback(new Error("名称不能包含特殊字符和空格"));
          } else {
            callback();
          }
        }
    };
    const vDes = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入模板内容"));
      } else {
        callback();
      }
    };
    const vCode = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入模板CODE"));
      } else {
        callback();
      }
    };
    return{
      list: [],  //数据
      listLoading: false,  //表格换场动画
      pickerOptions: pickerOptionsF(),
      pickerDate: pickerDateOneMonth(),
      template_list:[{
        id:0,name:"按模板名称",
      },{
        id:1,name:"按模板CODE",
      }],
      template_listState:[{
        id:0,name:"停用",
      },{
        id:1,name:"启用",
      }],
      formInline: {  //开始时间，结束时间
        begin_time: "",
        end_time: "",
        name:"",
        type:"",
        tem_type:0,
        code:"",
        enable:1
      },
      currentPage: 1,
      totalDataNumber: 0,
      tab_view:1,
      isDisabled:false,
      top_title: "添加模板",
      infoForm:{
        source:"1",
        type:"",
        code:"",
        name:"",
        content:""
      },
      rules: {
        name: [{ required: false, validator: vName, trigger: "blur" }],
        content: [{ required: false, validator: vDes, trigger: "blur" }],
        type:[{ required: true, validator: vTrad, trigger: 'change' }],
        code:[{ required: true, validator: vCode, trigger: 'change' }],
      },
    }
  },
  mounted() {
     this.listArray();
  },
  methods:{
    listArray(){  //获取数据
      optionMaxTime369(this.pickerDate).then(()=>{
        this.listLoading = true;
        this.list = [];
        if(this.formInline.tem_type==0){
          this.formInline.code="";
        }else{
          this.formInline.name="";
        }
        this.formInline.begin_time=this.pickerDate[0];
        this.formInline.end_time=this.pickerDate[1];
        getLinkInfoPage(this.formInline).then(response=>{
          this.totalDataNumber = response.data.count / 1;
          if (this.totalDataNumber == 0) {
            this.listLoading = false;
          } else {
            getLinkInfo(this.formInline).then(res=>{
              this.list = res.data;
              this.listLoading = false;
            });
          }
        });
      })
    },
    templateEnable(arrAy,type){
      this.$confirm(
          type?'是否确定启用？':'是否确定停用',
          "提示",
          { type: "warning" }
      ).then(() => {
        templateEnable({id:arrAy.id,is_enable:type}).then(res=>{
          if(res.code==1){
            this.listArray();
            this.$message.success(res.message);
          }
        })
      });
    },
    handleCurrentChange(val) {  //获取某个分页的数据
      this.listLoading = true;
      getLinkInfo(this.formInline,val).then(res=>{
        this.list = res.data;
        this.listLoading = false;
      }).catch(res => {
        this.listLoading = false;
      });
    },
    goPage(listArray){
      this.$router.push({
        name:"information/short_note",
        params:{data:listArray}
      })
    },
    addTypeClick(listArray) {
      this.tab_view=2;
      if(listArray){
        this.isDisabled=true;
        this.top_title="模板详情";
        this.infoForm={
          source:"1",
          type:listArray.type,
          code:listArray.code,
          name:listArray.name,
          content:listArray.content
        }
      }else{
        this.top_title="添加模板";
        this.isDisabled=false;
      }
    },
    backClick() {
      if (!this.isDisabled) {
        this.$confirm(
            "返回后已修改的数据不会保存，是否放弃本次操作？",
            "提示",
            {type: "warning"}
        ).then(() => {
          this.tab_view = 1;
          this.$refs.infoForm.resetFields();
        });
      }else{
        this.tab_view = 1;
        this.$refs.infoForm.resetFields();
      }
    },
    editClick(){  //保存
      this.$refs.infoForm.validate((valid) => {
        if(valid){
          this.$confirm(
              "请确保信息内容填写正确，保存后将不能进行修改，是否继续?",
              "提示",
              { type: "warning" }
          ).then(() => {
            createTemplate(this.infoForm).then(res=>{
              if(res.code==1){
                this.$message.success("创建成功");
                this.$refs.infoForm.resetFields();
                this.tab_view=1;
                this.listArray();
              }
            });
          });
        }
      });
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.customContainer {
  overflow-y: auto;
}
.longlinks{
  display:-webkit-box;
  text-overflow:ellipsis;
  overflow:hidden;
  -webkit-line-clamp: 2;
  -webkit-box-orient:vertical;
}
.main{
  .main_botton{
    margin-top: 20px;
    display: flex;
    align-items: center;
    justify-content: space-between;

    button{
      width: 100px;
      height: 35px;
      line-height: 10px;
    }
  }
}
.colortext{
  font-size: 14px;
  margin-top: 20px;
  p{
    margin: 0;
  }
}

.info {
  background: #fff;
  padding: 30px 0 10px;
  margin-bottom: 20px;
}

.tab_title {
  width: 200px;
  font-size: 20px;
  font-weight: bold;
  margin: 5px 0 20px 70px;
}
</style>
